package org.zachary.creditbusiness.commodityandhouse.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.zachary.creditbusiness.commodityandhouse.entity.CommodityOrder;
import org.zachary.creditbusiness.commodityandhouse.entity.Commodity;

import org.zachary.creditbusiness.commodityandhouse.mapper.CommodityOrderMapper;
import org.zachary.creditbusiness.commodityandhouse.mapper.CommodityMapper;
import org.zachary.creditbusiness.commodityandhouse.service.CommodityOrderService;
import org.zachary.creditbusiness.commodityandhouse.util.Result;
import org.zachary.creditbusiness.commodityandhouse.dto.OrderInitResponse;
import org.zachary.creditbusiness.hotel.util.KafkaProducerService;
import org.zachary.commonmodule.entity.MqTransmissionJson;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.time.Instant;
import java.util.List;
import java.util.UUID;

@Service
public class CommodityOrderServiceImpl implements CommodityOrderService {

    @Autowired
    private CommodityOrderMapper commodityOrderMapper;

    @Autowired
    private CommodityMapper commodityMapper;

    @Autowired
    private KafkaProducerService kafkaProducerService;

    @Override
    public Result<OrderInitResponse> initOrder(Integer commodityId, Integer userId) {
        try {
            // 查询商品信息
            Commodity commodity = commodityMapper.selectById(commodityId);
            if (commodity == null) {
                return Result.error("商品不存在");
            }

            // 检查库存
            if (commodity.getInventory() <= 0) {
                return Result.error("商品库存不足");
            }

            // 创建订单初始化响应
            OrderInitResponse response = new OrderInitResponse(
                    userId.byteValue(),
                    commodityId,
                    BigDecimal.ZERO // 默认无折扣
            );

            return Result.success(response);
        } catch (Exception e) {
            return Result.error("初始化订单失败: " + e.getMessage());
        }
    }

    @Override
    public Result placeOrder(CommodityOrder commodityOrder) {
        try {
            // 查询商品信息
            Commodity commodity = commodityMapper.selectById(commodityOrder.getCommodityId());
            if (commodity == null) {
                return Result.error("商品不存在");
            }

            // 检查库存
            if (commodity.getInventory() < commodityOrder.getAmount()) {
                return Result.error("商品库存不足");
            }

            // 计算总价
            BigDecimal unitPrice = commodity.getPrice();
            BigDecimal totalPrice = unitPrice.multiply(new BigDecimal(commodityOrder.getAmount()));

            // 设置订单信息
            commodityOrder.setOrderTime(new Timestamp(System.currentTimeMillis()));

            // 如果前端传递了费用明细，使用前端的计算结果；否则使用默认计算
            if (commodityOrder.getPrice() != null && commodityOrder.getPrice().doubleValue() > 0) {
                // 使用前端传递的费用明细
                // price, freightAmount, discountAmount, actualAmount 已由前端设置
            } else {
                // 使用后端默认计算
                commodityOrder.setPrice(totalPrice);
                commodityOrder.setFreightAmount(20.0); // 固定运费20元
                commodityOrder.setDiscountAmount(0.0); // 默认无折扣
                commodityOrder.setActualAmount(totalPrice.doubleValue() + 20.0); // 实际付费 = 商品总价 + 运费
            }

            // 根据支付方式设置订单状态
            if ("0".equals(commodityOrder.getMethod())) {
                // 立即支付
                commodityOrder.setFinished((byte) 2); // 已完成
                commodityOrder.setPayTime(new Timestamp(System.currentTimeMillis()));
            } else {
                // 货到付款
                commodityOrder.setFinished((byte) 1); // 货到付款待支付
            }

            // 保存订单
            int result = commodityOrderMapper.insert(commodityOrder);
            if (result > 0) {
                // 更新商品库存
                commodity.setInventory(commodity.getInventory() - commodityOrder.getAmount());
                commodityMapper.updateById(commodity);

                // 如果是立即支付，发送信用分消息
                if ("0".equals(commodityOrder.getMethod())) {
                    sendCreditScoreMessage(commodityOrder);
                }

                return Result.success("下单成功");
            } else {
                return Result.error("下单失败");
            }
        } catch (Exception e) {
            return Result.error("下单失败: " + e.getMessage());
        }
    }

    @Override
    public Result selectByUserId(Integer userId) {
        try {
            QueryWrapper<CommodityOrder> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", userId);
            queryWrapper.orderByDesc("order_time");

            List<CommodityOrder> orders = commodityOrderMapper.selectList(queryWrapper);
            return Result.success(orders);
        } catch (Exception e) {
            return Result.error("查询订单失败: " + e.getMessage());
        }
    }

    @Override
    public Result selectById(Integer id) {
        try {
            CommodityOrder order = commodityOrderMapper.selectById(id);
            if (order != null) {
                return Result.success(order);
            } else {
                return Result.error("订单不存在");
            }
        } catch (Exception e) {
            return Result.error("查询订单失败: " + e.getMessage());
        }
    }

    @Override
    public Result updateOrderStatus(Integer id, Byte status) {
        try {
            CommodityOrder order = commodityOrderMapper.selectById(id);
            if (order == null) {
                return Result.error("订单不存在");
            }

            order.setFinished(status);
            if (status == 2) { // 已完成
                order.setPayTime(new Timestamp(System.currentTimeMillis()));
            }

            int result = commodityOrderMapper.updateById(order);
            if (result > 0) {
                // 如果订单状态更新为已完成，发送信用分消息
                if (status == 2) {
                    sendCreditScoreMessage(order);
                }
                return Result.success("更新订单状态成功");
            } else {
                return Result.error("更新订单状态失败");
            }
        } catch (Exception e) {
            return Result.error("更新订单状态失败: " + e.getMessage());
        }
    }

    /**
     * 发送信用分消息到Kafka队列
     * @param order 商品订单
     */
    private void sendCreditScoreMessage(CommodityOrder order) {
        try {
            MqTransmissionJson message = new MqTransmissionJson(
                    UUID.randomUUID().toString(), // uuid
                    order.getUserId().intValue(), // userId
                    5, // serviceType: DiscountedShopping对应的枚举值
                    false, // isOverdue: 信用购物没有逾期概念
                    0, // overduePeriod: 无逾期期数
                    true, // isPaid: 已支付
                    order.getActualAmount(), // amount: 实际支付金额
                    "信用购物支付完成", // desc
                    Instant.now(), // dueTime: 当前时间
                    Instant.now() // finishTime: 当前时间
            );

            kafkaProducerService.sendJsonMessage("TestTopic", message);
            System.out.println("信用购物支付完成，已发送信用分消息: " + message);
        } catch (Exception e) {
            System.err.println("发送信用分消息失败: " + e.getMessage());
            e.printStackTrace();
        }
    }

}
